import axios, {AxiosRequestConfig} from 'axios'

const httpInstance = axios.create({
    baseURL: 'http://127.0.0.1:10000',
    timeout: 5000
})

// 拦截器

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    // const userStore = useUserStore()
    // 2. 按照后端的要求拼接token数据
    // const token = userStore.userInfo.token
    // if (token) {
    //     config.headers.Authorization = `Bearer ${token}`
    // }
    return config
}, e => Promise.reject(e))

interface ResponseType<T> {
    code: number;
    msg: string;
    data: T;
}

export default async <T>(config: AxiosRequestConfig): Promise<ResponseType<T>> => {
    try {
        const {data} = await httpInstance.request<ResponseType<T>>(config)
        if (data.code !== 0) {
            console.error(data.msg)
        }
        return data
    } catch (err) {
        console.error(err)
        return {
            code: -1,
            msg: '求知错误',
            data: null as any,
        }
    }
}
